package com.cje.login;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Auther: ChenJinEn
 * @Date: 2020/8/9 19:27
 * @Description: //TODO 拦截器,拦截方法url
 */
public class LoginIntercepter implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //登录时不做拦截
        if (request.getRequestURL().toString().contains("/Login")) {
            return true;
        }
        //注册时候不拦截
        if (request.getRequestURL().toString().contains("/Register")) {
            return true;
        }
        //退出登录不拦截
        if (request.getRequestURL().toString().contains("/LoginOut")) {
            return true;
        }

        //其他根据条件拦截
        if (request.getSession().getAttribute("user") != null) {
            //session中或者redis中存有用户信息,放行
            return true;
        }else {
            //转发到登录页面去登录
            request.getRequestDispatcher("/WEB/jsp/login.jsp").forward(request, response);
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("在处理请求");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("请求已处理完毕");
    }
}
